package cn.lrwjz.androidguide.util;

import android.os.Handler;
import android.os.Looper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * HTTP网络请求工具类
 */
public class HttpUtil {
    private static final int TIMEOUT = 10000; // 超时时间10秒
    private static final String CHARSET = "UTF-8"; // 字符编码
    private static final ExecutorService executor = Executors.newCachedThreadPool();
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());

    /**
     * GET请求
     *
     * @param urlString 请求URL
     * @param headers   请求头
     * @param callback  回调接口
     */
    public static void get(String urlString, Map<String, String> headers, HttpCallback callback) {
        executor.execute(() -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(urlString);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(TIMEOUT);
                connection.setReadTimeout(TIMEOUT);

                // 添加请求头
                if (headers != null) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        connection.setRequestProperty(entry.getKey(), entry.getValue());
                    }
                }

                // 发起请求
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    String response = readResponse(connection.getInputStream());
                    notifySuccess(callback, response);
                } else {
                    notifyError(callback, new IOException("HTTP " + responseCode));
                }
            } catch (Exception e) {
                notifyError(callback, e);
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        });
    }

    /**
     * POST请求
     *
     * @param urlString 请求URL
     * @param headers   请求头
     * @param body      请求体
     * @param callback  回调接口
     */
    public static void post(String urlString, Map<String, String> headers, String body, HttpCallback callback) {
        executor.execute(() -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(urlString);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(TIMEOUT);
                connection.setReadTimeout(TIMEOUT);
                connection.setDoOutput(true);
                connection.setDoInput(true);

                // 添加请求头
                if (headers != null) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        connection.setRequestProperty(entry.getKey(), entry.getValue());
                    }
                }

                // 写入请求体
                if (body != null) {
                    try (OutputStream os = connection.getOutputStream()) {
                        byte[] input = body.getBytes(StandardCharsets.UTF_8);
                        // 字节数组写入到输出流中，实际上是将请求体内容发送到服务器
                        os.write(input, 0, input.length);
                    }
                }

                // 发起请求
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    String response = readResponse(connection.getInputStream());
                    notifySuccess(callback, response);
                } else {
                    notifyError(callback, new IOException("HTTP " + responseCode));
                }
            } catch (Exception e) {
                notifyError(callback, e);
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        });
    }

    /**
     * 读取响应内容
     */
    private static String readResponse(InputStream is) throws IOException {
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, CHARSET))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        return response.toString();
    }

    /**
     * 通知请求成功
     */
    private static void notifySuccess(HttpCallback callback, String response) {
        if (callback != null) {
            // 将一个任务（即 callback.onSuccess(response) 的调用）放到主线程的消息队列中执行
            mainHandler.post(() -> callback.onSuccess(response));
        }
    }

    /**
     * 通知请求失败
     */
    private static void notifyError(HttpCallback callback, Exception e) {
        if (callback != null) {
            mainHandler.post(() -> callback.onError(e));
        }
    }

    /**
     * HTTP请求回调接口
     */
    public interface HttpCallback {
        void onSuccess(String response);
        void onError(Exception e);
    }
} 